
/**
 * RSA 加密
 */
// 使用encryptlong无法解密长字符
// import Encryptlong from 'encryptlong'
export default class EncryptlongUtil {
  init(isTest) {
    this.isTest = isTest
    // this.encryptlong = new Encryptlong()
    // eslint-disable-next-line no-undef
    this.encryptlong = new JSEncrypt()
  }
  setPublicKey(key) {
    this.encryptlong.setPublicKey(key)
    this.publicKey = key
  }
  getPublicKey() {
    return this.publicKey
  }
  setPrivateKey(key) {
    // key = `-----BEGIN RSA PRIVATE KEY-----
    // ${key}
    // -----END RSA PRIVATE KEY-----`
    this.privateKey = key
    this.encryptlong.setPrivateKey(key)
  }
  getPrivateKey() {
    return this.privateKey
  }
  /**
    * 获取加密数据
    * @param {*} data
    * @returns
    */
  getEncryptedStr(data) {
    const encryptedStr = this.encryptlong.encrypt(data)
    if (this.isTest) {
      console.log('----------RSA加密后数据----------')
      console.log(encryptedStr)
    }
    // this.decrypt(encryptedStr)
    return encryptedStr
  }
  /**
  * 加密
  * @param {*} data 需要加密的数据，string或object
  * @returns
  */
  encrypt(data) {
    data = this.toStr(data)
    if (!data) {
      return ''
    }
    if (typeof (data) === 'object') {
      data = JSON.stringify(data)
    }
    if (this.isTest) {
      console.log('----------RSA被加密数据----------')
      console.log(data)
      console.log('----------RSA加密key(只在测试环境会打印)----------')
      console.log(this.getPublicKey())
    }
    // 加密数据
    return this.getEncryptedStr(data)
  }
  toStr(data) {
    if (!data) {
      return ''
    }
    if (typeof (data) === 'object') {
      data = JSON.stringify(data)
    }
    return data
  }
  /**
  * 解密
  * @param {*} data string或object
  * @returns
  */
  decrypt(data) {
    data = this.toStr(data)
    if (!data) {
      return ''
    }
    if (this.isTest) {
      console.log('----------RSA解密数据----------')
      console.log(data)
      console.log('----------RSA解密key----------')
      console.log(this.getPrivateKey())
    }

    // const decryptStr = this.encryptlong.decryptLong(data)
    const decryptStr = this.encryptlong.decrypt(data)
    if (this.isTest) {
      console.log('----------RSA解密后数据----------')
      console.log(decryptStr)
    }
    let decryptObj = decryptStr
    try {
      decryptObj = JSON.parse(decryptStr)
    } catch (e) {
      console.warn('数据类型转换失败:' + decryptStr)
      console.warn(e)
    }
    return decryptObj
  }
}

